package com.crawler.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HttpCustomUtil {
	/**
	 * 获取图片byte[]
	 * 
	 * @param url
	 *            图片url
	 * @param timeout
	 *            请求超时时间
	 * @param headers
	 *            请求头
	 * @return
	 */
	public static byte[] GetImage(String url, int timeout, Map<String, String> headers) {
		byte[] data = null;
		try {

			URL u = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u.openConnection();
			if (headers != null && headers.size() > 0) {
				Set<String> keys = headers.keySet();
				Iterator<String> it = keys.iterator();
				while (it.hasNext()) {
					String k = it.next().toString();
					if (k != null) {
						conn.setRequestProperty(k, headers.get(k));
					}
				}
			}
			conn.setConnectTimeout(timeout);
			InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
			data = readInputStream(inStream);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return data;
	}

	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[2048];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}
}
